package com.example.tuter;

import static com.example.tuter.util.Constant.baseUrl;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.WindowManager;

import androidx.core.app.NotificationCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSON;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.example.tuter.activity.BaseActivity;
import com.example.tuter.activity.NotificationReactActivity;
import com.example.tuter.adapter.SectionsPagerAdapter;
import com.example.tuter.entity.Message;
import com.example.tuter.entity.Post;
import com.example.tuter.fragment.FragmentCommunityBase;
import com.example.tuter.fragment.FragmentMine;
import com.example.tuter.fragment.FragmentXXMH;
import com.example.tuter.util.Constant;
import com.example.tuter.util.httpUtil.HttpFunction.CommunityAPI;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import retrofit2.Call;
import retrofit2.Callback;

public class MainActivity extends BaseActivity implements BottomNavigationBar.OnTabSelectedListener, ViewPager.OnPageChangeListener {

    private ViewPager viewpager;
    private BottomNavigationBar bottomnavigationBar;
    private List<Fragment> fragments;
    private static final String TAG = MainActivity.class.getSimpleName();
    private Typeface font;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        super.onCreate(savedInstanceState);

        font = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        //websocket();//开始websocket
        initBottomNavigationBar();
        initViewPager();

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void initData() {

    }



    @Override
    protected void bindEvent() {

    }

    //初始化页面
    @Override
    protected void initView() {
        setContentView(R.layout.activity_main);



        NotificationClickReceiver notificationClickReceiver = new NotificationClickReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_BROADCAST);
        registerReceiver(notificationClickReceiver, intentFilter);


        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        viewpager = findViewById(R.id.viewpager);

        bottomnavigationBar = findViewById(R.id.bottom);


    }

    @Override
    protected int getLayoutID() {
        return 0;
    }

    //初始化底部tabbar
    @SuppressLint("ResourceType")
    private void initBottomNavigationBar() {
        //配置底部导航栏
        bottomnavigationBar.setTabSelectedListener(this);
        bottomnavigationBar.clearAll();
        bottomnavigationBar.setMode(BottomNavigationBar.MODE_FIXED);  //自适应大小
        bottomnavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_DEFAULT);
        bottomnavigationBar.setBarBackgroundColor(R.color.white)
                .setActiveColor(R.color.colorBasel)
                .setInActiveColor(R.color.black);
        bottomnavigationBar.addItem(new BottomNavigationItem(R.drawable.homepage_fill, R.string.bar_home).setInactiveIconResource(R.drawable.homepage))
                .addItem(new BottomNavigationItem(R.drawable.mobilephone_fill, R.string.bar_server).setInactiveIconResource(R.drawable.mobilephone))
                .addItem(new BottomNavigationItem(R.drawable.mine_fill, R.string.bar_mine).setInactiveIconResource(R.drawable.mine))
                .setFirstSelectedPosition(0)
                .initialise();
    }


    private void initViewPager() {

        //配置Viewpager
        viewpager.setOffscreenPageLimit(3);

        fragments = new ArrayList<Fragment>();
        fragments.add(new FragmentCommunityBase());
        fragments.add(new FragmentXXMH());
        fragments.add(new FragmentMine());
        viewpager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager(), fragments));
        viewpager.addOnPageChangeListener(this);
        viewpager.setCurrentItem(0);

    }


    @Override
    public void onTabSelected(int position) {
        viewpager.setCurrentItem(position);
    }

    @Override
    public void onTabUnselected(int position) {

    }

    @Override
    public void onTabReselected(int position) {

    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int i) {
        bottomnavigationBar.selectTab(i);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    public void websocket() {
        if (Constant.userInfo == null) return;
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(3, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(3, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(3, TimeUnit.SECONDS)//设置连接超时时间
                .build();
        //连接地址
        String url = "ws://" + baseUrl + "/websocket/" + Constant.userInfo.getStudentId();
        //构建一个连接请求对象
        Request request = new Request.Builder().get().url(url).build();
        WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                super.onOpen(webSocket, response);
                //连接成功...
                Log.d(TAG, "onOpen: ");
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                super.onMessage(webSocket, text);
                getNotificationData(text);
            }


            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                super.onClosed(webSocket, code, reason);
                //连接关闭...
                Log.d(TAG, "onClosed: ");
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable throwable, Response response) {
                super.onFailure(webSocket, throwable, response);
                //连接失败...
                Log.d(TAG, "onFailure: ");
            }
        });
    }

    public void getNotificationData(String json) {
        try {
            List<com.example.tuter.entity.Notification> notifications = JSON.parseArray(json, com.example.tuter.entity.Notification.class);
            //获取到通知
            for (com.example.tuter.entity.Notification notification :
                    notifications) {

                //根据通知信息
                switch (notification.getType()) {
                    //点赞
                    case 1:
                        Intent intent = new Intent(Constant.ACTION_BROADCAST);

                        intent.putExtra("id", notification.getId());

                        int id1 = (int) (System.currentTimeMillis() / 1000);

                        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                        NotificationManager notificationManager = (NotificationManager)
                                getSystemService(Context.NOTIFICATION_SERVICE);
                        if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                            NotificationChannel notificationChannel = new NotificationChannel("myChannelId", "channelname"
                                    , NotificationManager.IMPORTANCE_HIGH);
                            notificationManager.createNotificationChannel(notificationChannel);
                        }
                        Notification aNotification = new NotificationCompat.Builder(this, "myChannelId")
                                .setContentTitle("你有一条新消息")
                                .setContentText(notification.getContent())
                                .setWhen(System.currentTimeMillis())
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                                .setContentIntent(pendingIntent)
                                .setAutoCancel(true)
                                .build();
                        notificationManager.notify(1, aNotification);
                        //帖子被回复
                    case 2:
                        break;
                    case 3://楼层被回复
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //弹窗通知
    private class NotificationClickReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            setIntent(intent);
            intent = getIntent();
            Integer pid = intent.getIntExtra("pid", -1);
            getPostByPid(pid);

        }
    }

    public void getPostByPid(final Integer pid) {
        try {
            CommunityAPI communityAPI = Constant.r.create(CommunityAPI.class);
            Call<Message<Post>> postByPid = communityAPI.getPostByPid(Integer.valueOf(pid));
            postByPid.enqueue(new Callback<Message<Post>>() {
                @Override
                public void onResponse(Call<Message<Post>> call, retrofit2.Response<Message<Post>> response) {
                    //设置点击通知
                    assert response.body() != null;
                    Intent intent1 = new Intent(MainActivity.this, NotificationReactActivity.class);
                    intent1.putExtra("post", response.body().getData());
                    startActivity(intent1);
                }

                @Override
                public void onFailure(Call<Message<Post>> call, Throwable t) {

                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
